#!/bin/sh
set -x
# 修改默认源
sed -i "s/^#http/http/" /etc/apk/repositories
# 添加源
add_repo() {
  cat >>/etc/apk/repositories <<"EOF"
http://mirrors.aliyun.com/alpine/edge/community
http://mirrors.aliyun.com/alpine/edge/testing
EOF
}

conf_bash() {
  apk add bash bash-completion
  # 配置 bash
  sed -i 's/ash/bash/g' /etc/passwd
  cat >/etc/profile.d/self.sh <<"eof"
alias update='apk update && apk upgrade'
export HISTTIMEFORMAT="%d/%m/%y %T "
export PS1='\u@\h:\W \\$ '
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'
source /usr/share/bash-completion/bash_completion
eof
}
conf_ntp() {
  apk add tzdata
  # 配置时区
  install -Dm 0644 /usr/share/zoneinfo/Asia/Shanghai /etc/zoneinfo/Asia/Shanghai
  export TZ='Asia/Shanghai'
  echo "export TZ='$TZ'" >>/etc/profile.d/timezone.sh
  sed -i "s|pool.ntp.org|ntp.aliyun.com|g" /etc/chrony/chrony.conf
  rc-service chronyd restart
}

install_packages() {
  packages="curl vim wget cni-plugin-flannel cni-plugins flannel flannel-contrib-cni kubelet kubeadm kubectl containerd containerd-ctr uuidgen nfs-utils"
  for package in ${packages}; do
    apk add ${package}
  done

}
init_kube() {
  grep aliyun /etc/containerd/config.toml >>/dev/null || curl -o /etc/containerd/config.toml https://gitee.com/chongxs/opscript/raw/master/config/containerd.toml
  rc-service containerd restart
  kubeadm config images pull --image-repository registry.aliyuncs.com/google_containers
  kubeadm init --node-name=$(hostname) --image-repository registry.aliyuncs.com/google_containers
}

main() {
  grep edge /etc/apk/repositories >/dev/null || add_repo
  apk update
  apk upgrade
  if [ $SHELL != "/bin/bash" ]; then
    conf_bash
    echo "Switch the shell and take effect after logging in again."
    exit 0
  fi
  grep aliyun /etc/chrony/chrony.conf >/dev/null || conf_ntp
  # 关闭swap
  swapoff -a
  sed -i "s|.*swap.*|#&|" /etc/fstab

  # 加载模块
  echo "br_netfilter" >/etc/modules-load.d/k8s.conf
  modprobe br_netfilter
  # 优化内核
  cat >>/etc/sysctl.conf <<"EOF"
net.bridge.bridge-nf-call-iptables=1
net.ipv4.ip_forward= 1
EOF
  sysctl -p

  # 处理监控
  mount --make-rshared /
  echo "#!/bin/sh" >/etc/local.d/sharemetrics.start
  echo "mount --make-rshared /" >>/etc/local.d/sharemetrics.start
  chmod +x /etc/local.d/sharemetrics.start
  rc-update add local
  #Fix id error messages
  uuidgen >/etc/machine-id

  #Add services
  #rc-update add docker
  rc-update add containerd
  rc-update add kubelet
  rc-service containerd start
  install_packages

  #  判断 hostname，再判断 hosts 文件
  if [ $(hostname) == "localhost" ]; then
    echo "Please modify the hostname"
    exit 1
  else
    mem=$(free | awk 'NR==2{print $2}')
    cores=$(grep "cpu cores" /proc/cpuinfo | uniq | cut -d: -f2)
    if [[ $mem -gt 204800 ]] && [[ $cores -gt 1 ]]; then
      echo "Start initialization"
      init_kube
    else
      echo "If the configuration is low, upgrade the configuration"
    fi
  fi

}
main
